﻿using System;
using System.Collections.Generic;
using System.Drawing;
using Moonlite.Data.Mpq;
using Moonlite.ExtensionApi.ControlInterfaces;

namespace Moonlite.Modules.Editors.DataTools
{
    public class DataCustomFolderNode : AbstractCustomFolderNode
    {
        public const string DataFilesMpqFolderPath = "Base.SC2Data\\GameData\\";
        public const string DataFilesFileMask = "*.xml";
        internal static DataCustomFolderNode instance;
        public override bool CanDragDropToChildren
        {
            get { return false; }
        }

        private TMPQFileInfo[] GetFilesInMpqFolder(TMPQArchive archive, string folderPath)
        {
            List<TMPQFileInfo> fileInfos = new List<TMPQFileInfo>();
            foreach (TMPQFileInfo fileInfo in archive.GetFiles(DataFilesFileMask))
            {
                if (fileInfo.FileName.StartsWith(folderPath))
                {
                    fileInfos.Add(fileInfo);
                }
            }

            if (fileInfos.Count > 0)
            {
                return fileInfos.ToArray();
            }

            return null;
        }

        internal void UpdateChildren()
        {
            Nodes.Clear();
            using (TMPQArchive archive = new TMPQArchive(Project.GetMapPath()))
            {
                TMPQFileInfo[] fileInfos = GetFilesInMpqFolder(archive, DataFilesMpqFolderPath);
                if (fileInfos != null)
                {
                    foreach (TMPQFileInfo fileInfo in fileInfos)
                    {
                        DataCustomNode node = new DataCustomNode(ProjectManager);
                        node.Text = fileInfo.FileName.Replace(DataFilesMpqFolderPath, "");
                        node.Tag = fileInfo.FileName;
                        Nodes.Add(node);
                        node.UpdateImage();
                    }
                }
            }
        }

        internal void UpdateImage()
        {
            ClosedImage = Image.FromStream(typeof(DataCustomNode).Assembly.GetManifestResourceStream("Moonlite.Modules.Editors.DataTools.Resources.Icons.ProjectManager.DataFolder_Closed.bmp"));
            OpenImage = Image.FromStream(typeof(DataCustomNode).Assembly.GetManifestResourceStream("Moonlite.Modules.Editors.DataTools.Resources.Icons.ProjectManager.DataFolder_Opened.bmp"));
        }

        public DataCustomFolderNode(IProjectManager projectManager)
            : base(projectManager)
        {
            instance = this;
        }
    }
}
